package com.example.once.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.once.common.Result;
import com.example.once.entity.Storage;
import com.example.once.mapper.StorageMapper;
import com.example.once.common.PageQuery;
import com.example.once.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xinTong
 * @since 2023-12-15
 */
@RestController
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService service;
    @Autowired
    private StorageMapper storageMapper;

    /**
     * 增
     * @param storage
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Storage storage){
        return service.save(storage) ? Result.suc() : Result.fail();
    }

    /**
     * 删
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public Result delete(@RequestParam Integer id){
        return service.removeById(id) ? Result.suc() : Result.fail();
    }

    /**
     * 改
     * @param storage
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Storage storage){
        return service.updateById(storage) ? Result.suc() : Result.fail();
    }

    /**
     * 查
     * @param query
     * @return
     */
    @PostMapping("/select")
    public Result select(@RequestBody PageQuery query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");

        IPage<Storage> page = new Page<>(query.getPageNum(), query.getPageSize());

        LambdaQueryWrapper<Storage> storageLambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(name)) {
            storageLambdaQueryWrapper.like(Storage::getName, name);
        }

        IPage<Storage> iPage = storageMapper.selectPage(page, storageLambdaQueryWrapper);
        System.out.println("总页数： " + page.getPages());
        System.out.println("总记录数： " + page.getTotal());

        return Result.suc(iPage.getRecords(), iPage.getTotal());
    }

    /**
     * 查
     */
    @GetMapping("/list1")
    public Result select1() {
        List<Storage> list = service.list();
        return Result.suc(list);
    }
}
